package com.sun.tast;

import com.sun.service.ITimeService;
import com.sun.service.impl.CronServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;

/**
 * @author user
 */
@Configuration
@EnableScheduling
public class DynamicScheduleTask implements SchedulingConfigurer {

    @Autowired
    private CronServiceImpl cronServiceImpl;

    @Autowired
    private ITimeService iTimeService;

    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    int i = iTimeService.updateTimeForCreateTime();
                    System.out.println(i);
                    //2.1 从数据库获取执行周期
                    String cron = null;
                    try {
                        cron = cronServiceImpl.getFirstName().get(0).getCron();
                        return new CronTrigger(cron).nextExecutionTime(triggerContext);
                    } catch (Exception e) {
                        return null;
                    }
                }
        );
    }
}
